// auth.ts - 登录认证工具

export interface UserInfo {
  id: number;
  phone: string;
  nickName: string;
  avatar: string;
  token: string;
}

export class AuthManager {
  // 检查是否登录
  static isLoggedIn(): boolean {
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    const token = wx.getStorageSync('token')
    return !!(isLoggedIn && token)
  }

  // 获取用户信息
  static getUserInfo(): UserInfo | null {
    const userInfo = wx.getStorageSync('userInfo')
    return userInfo || null
  }

  // 获取token
  static getToken(): string {
    return wx.getStorageSync('token') || ''
  }

  // 跳转到登录页面
  static redirectToLogin() {
    console.log('AuthManager redirectToLogin')
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }

  // 检查并跳转到登录（用于页面加载时调用）
  static checkAuthAndRedirect(): boolean {
    if (!this.isLoggedIn()) {
      this.redirectToLogin()
      return false
    }
    return true
  }

  // 退出登录
  static logout() {
    console.log('AuthManager logout')
    wx.removeStorageSync('isLoggedIn')
    wx.removeStorageSync('token')
    wx.removeStorageSync('userInfo')
    
    // 跳转到登录页
    wx.reLaunch({
      url: '/pages/login/login'
    })
  }

  // 保存登录信息
  static saveLoginInfo(userInfo: UserInfo) {
    wx.setStorageSync('userInfo', userInfo.member)
    wx.setStorageSync('token', userInfo.token)
    wx.setStorageSync('isLoggedIn', true)
  }
}